package com.zjhome.cloudnote.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.zjhome.cloudnote.constant.ErrorCode;
import com.zjhome.cloudnote.exception.BaseException;
import com.zjhome.cloudnote.service.UserService;

/**
 * @author 0283000121
 *
 */

public abstract class BaseController {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	protected UserService	userService;
	
	@Autowired
	protected BCryptPasswordEncoder	bCryptPasswordEncoder;
	
	
	/**
	 * 获取用户所拥有的权限列表
	 * 
	 * @return
	 */
	public List<String> getAuthentication() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
		List<String> list = new ArrayList<>();
		
		for (GrantedAuthority grantedAuthority : authorities) {
			logger.info("权限列表: {}", grantedAuthority.getAuthority());
			list.add(grantedAuthority.getAuthority());
		}
		
		return list;
	}
	
	/**
	 * 获取用户id
	 * 
	 * @return
	 */
	public String getUserId() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		return (String)authentication.getPrincipal();
	}
	
	/**
	 * 统一请求异常处理（请求）
	 * 
	 * @param request
	 * @param exception
	 * @return
	 * @throws Exception
	 */
	@ExceptionHandler(value = BaseException.class)
	public Map<String, Object> rquestExceptionHandler(HttpServletRequest request, BaseException exception) throws Exception {
		
		Map<String,Object> map = new HashMap<>();		
		ErrorCode errorCode = exception.getErrorCode();
				
//		map.put("status", errorCode.getCode());
//		map.put("remark", errorCode.getRemark());
		
//		Map<String, Object> err = new HashMap<>();
//		err.put("code", errorCode.getCode());
//		err.put("remark", exception.getMessage());
//		
//		map.put("error", err);
		
		map.put("status", errorCode.getCode());
		map.put("error", exception.getMessage());		
		
		return map;
	}
	
}
